package com.chennan.ymlanalysis.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.*;

/**
 * @author chennan
 * @create 2022-05
 */
public class YmlConfiguration {

    private DumperOptions options = new DumperOptions();
    private File file;
    private Object CONFIG_MAP;
    private Yaml yaml;
    {
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    }
    public YmlConfiguration(String path) {
        this.file = new File(path);
        InputStream ymlInputSteam = null;
        try {
            ymlInputSteam = new FileInputStream(file);
            yaml = new org.yaml.snakeyaml.Yaml(options);
            CONFIG_MAP = yaml.load(ymlInputSteam);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if(ymlInputSteam!=null){
                    ymlInputSteam.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                ymlInputSteam=null;
            }
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> transForm(JSONObject config) {
        Map<String, Object> map = new HashMap<>();
        for (String key : config.keySet()) {
            if (key.matches(".+\\[\\d\\]")) {
                String replaceAll = key.replaceAll("\\[\\d\\]", "");
                if (map.containsKey(replaceAll)) {
                    Object object = map.get(replaceAll);
                    if (object instanceof List) {
                        ((List) object).add(config.get(key));
                    }
                } else {
                    List<Object> list = new ArrayList<>();
                    list.add(config.get(key));
                    map.put(replaceAll, list);
                }
            } else {
                map.put(key, config.get(key));
            }
        }
        return map;
    }

    /**
     * 根据键获取值
     *
     * @param key 键
     * @return 查询到的值
     */
    @SuppressWarnings("unchecked")
    public Object getByKey(String key) {
        String[] keys = key.split("\\.");
        Object configMap = CONFIG_MAP;
        for (String s : keys) {
            if (configMap instanceof Map) {
                configMap = ((Map<String, Object>) configMap).get(s);
            } else {
                break;
            }
        }
        return configMap == null ? "" : configMap;
    }

    public Properties ListYml() {
        ClassPathResource classPathResource = new ClassPathResource("/"+this.file.getName());
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(classPathResource);
        Properties object = yamlFactory.getObject();
        return object;
    }

    public void saveOrUpdateByKey(String key, Object value) throws IOException {
        KeyAndMap keyAndMap = new KeyAndMap(key).invoke();
        key = keyAndMap.getKey();
        Map<String, Object> map = keyAndMap.getMap();
        map.put(key, value);
        // 将数据重新写回文件
        FileWriter fileWriter = new FileWriter(file);
        yaml.dump(CONFIG_MAP, fileWriter);
        fileWriter.close();
    }

    public void removeByKey(String key) throws Exception {
        KeyAndMap keyAndMap = new KeyAndMap(key).invoke();
        key = keyAndMap.getKey();
        Map<String, Object> map = keyAndMap.getMap();
        Map<String, Object> fatherMap = keyAndMap.getFatherMap();
        map.remove(key);
        if (map.size() == 0) {
            Set<Map.Entry<String, Object>> entries = fatherMap.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                if (entry.getValue() == map) {
                    fatherMap.remove(entry.getKey());
                }
            }
        }
        FileWriter fileWriter = new FileWriter(file);
        yaml.dump(CONFIG_MAP, fileWriter);
        fileWriter.close();
    }

    private class KeyAndMap {
        private String key;
        private Map<String, Object> map;
        private Map<String, Object> fatherMap;

        public KeyAndMap(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }

        public Map<String, Object> getMap() {
            return map;
        }

        public Map<String, Object> getFatherMap() {
            return fatherMap;
        }

        @SuppressWarnings("unchecked")
        public KeyAndMap invoke() {
            if (file == null) {
                System.err.println("请设置文件路径");
            }
            if (null == CONFIG_MAP) {
                CONFIG_MAP = new LinkedHashMap<>();
            }
            String[] keys = key.split("\\.");
            key = keys[keys.length - 1];
            map = (Map<String, Object>) CONFIG_MAP;
            for (int i = 0; i < keys.length - 1; i++) {
                String s = keys[i];
                if (map.get(s) == null || !(map.get(s) instanceof Map)) {
                    map.put(s, new HashMap<>(4));
                }
                fatherMap = map;
                map = (Map<String, Object>) map.get(s);
            }
            return this;
        }
    }
}
